import React, { Component } from 'react';
import { View, Text, Animated, Dimensions, PanResponder, Image, Easing } from 'react-native';

const { width } = Dimensions.get('window');

class SwiperView extends Component {
	constructor(props) {
		super(props);
		this.state = {
			sports: new Animated.Value(-width), // 设置初始值
			styles: {},
			boxNumber: this.props.children.length,
			childPages: this.props.children,
			curIndex: 1,
			animateRun: false, // 动画是否完成
		};
		this.startTimestamp = 0; // 拖拽开始时间戳（用于计算滑动速度）
		this.endTimestamp = 0; // 拖拽结束时间戳用于计算滑动速度）
		this.page = 1; // 首次展示第一条数据（page 最小值为0，即从0开始，1为第二个条目）
	}
	componentWillMount() {
		const { children, style } = this.props;
		const newPages = [children[children.length - 1], ...children, children[0]];
		this.setState({
			styles: {
				width: (children.length + 1) * width,
			},
			childPages: [...newPages],
		});
		this.panResponder();
	}

	panResponder() {
		this._panResponder = PanResponder.create({
			onMoveShouldSetPanResponder: (evt, gestureState) => true,
			onPanResponderTerminationRequest: (evt, gestureState) => true,
			onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
			onPanResponderGrant: (evt, gestureState) => {
				// 滑动开始，记录时间戳
				this.startTimestamp = evt.nativeEvent.timestamp;
			},
			onPanResponderMove: (evt, gestureState) => {
				// 滑动横向距离
				let x = gestureState.dx;
				// 实时改变滑动位置
				if (x > 0) {
					this.setState({
						sports: new Animated.Value(-this.page * width + x),
					});
				} else {
					this.setState({
						sports: new Animated.Value(x - this.page * width),
					});
				}
			},
			onPanResponderRelease: (evt, gestureState) => {
				const { boxNumber } = this.state;
				// 滑动结束时间戳
				this.endTimestamp = evt.nativeEvent.timestamp;
				// 滑动距离，根据滑动距离与时间戳计算是否切换到下一个条目
				let x = gestureState.dx;

				console.log('gryer',this.autoPlayTimer);

				if (x > 0) {
					// 滑动距离大于屏幕1半，开启动画，滑动到下一个界面，或者滑动速度很快，并且滑动距离大于20，也滑动到下一个条目
					if (x > width / 2 || (this.endTimestamp - this.startTimestamp < 300 && x > 20)) {
						this.page -= 1;
					}
					Animated.timing(this.state.sports, {
						toValue: -this.page * width,
						duration: 200,
					}).start((state) => {
						// 动画完成，判断是否需要重置位置
						if (state.finished) {
							if (this.page <= 0) {
								this.page = boxNumber;
								this.setState({
									sports: new Animated.Value(-boxNumber * width),
								});
							}
						}
					});
				} else {
					x = Math.abs(x);
					// 滑动距离大于屏幕1半，开启动画，滑动到下一个界面，或者滑动速度很快，并且滑动距离大于20，也滑动到下一个条目
					if (x > width / 2 || this.endTimestamp - this.startTimestamp < 300) {
						this.page += 1;
						this.setState({
							animateRun: true,
						});
					}
					Animated.timing(this.state.sports, {
						toValue: -this.page * width,
						duration: 200,
					}).start((state) => {
						// 动画完成，判断是否需要重置位置
						if (state.finished) {
							if (this.page >= boxNumber + 1) {
								this.page = 1;
								this.setState({
									sports: new Animated.Value(-width * this.page),
								});
							}
						}
					});
				}
				this.setState({
					curIndex: this.page,
				});
			},
			onShouldBlockNativeResponder: (evt, gestureState) => {
				return false;
			},
		});
	}

	// 指示器
	renderPagination = () => {
		const { children } = this.props;
		let { curIndex, boxNumber } = this.state;

		// 判断 0 和 5 的情况
		if (curIndex === 0) {
			curIndex = boxNumber - 1;
		} else if (curIndex === boxNumber + 1) {
			curIndex = 0;
		} else {
			curIndex--;
		}

		return children.map((item, index) => {
			return (
				<Text
					key={index}
					style={[stylesheel.indicators, curIndex === index && stylesheel.white]}
				></Text>
			);
		});
	};

	// 定时器执行函数
	runSetTimeOut = () => {
		if (this.page === 4) {
			this.page = 1;
		} else {
			this.page++;
		}
		console.log('gry', this.state.animateRun);
		this.autoPlayTimer = setTimeout(() => {
			const newSports = new Animated.Value(-width * (this.page - 1));
			this.setState({
				sports: newSports,
			});
			Animated.timing(this.state.sports, {
				toValue: -this.page * width,
				duration: 4000,
				useNativeDriver: false,
			}).start((state) => {
				if (state.finished) {
					this.setState(
						{
							curIndex: this.page,
						},
						() => {
							this.runSetTimeOut();
						}
					);
				}
			});
		}, 4000);
	};

	componentWillUnmount() {
		console.log('gry','清除');
		this.autoPlayTimer && clearTimeout(this.autoPlayTimer);
	}

	render() {
		const { styles, childPages, sports } = this.state;
		return (
			<View>
				<Animated.View
					style={{ ...this.props.style, ...styles, left: sports }}
					{...this._panResponder.panHandlers}
				>
					{childPages}
				</Animated.View>
				{/* 指示器 */}
				<View style={stylesheel.pagination}>{this.renderPagination()}</View>
			</View>
		);
	}

	componentDidMount() {
		this.runSetTimeOut();
	}
}

const stylesheel = {
	pagination: {
		position: 'absolute',
		bottom: 10,
		flexDirection: 'row',
		width: '100%',
		justifyContent: 'center',
	},
	indicators: {
		width: 8,
		height: 8,
		backgroundColor: '#2e7bff',
		marginLeft: 10,
		borderTopLeftRadius: 10,
		borderTopRightRadius: 10,
		borderBottomLeftRadius: 10,
		borderBottomRightRadius: 10,
	},
	white: {
		backgroundColor: '#fffffe',
	},
};

export default class App extends Component {
	render() {
		return (
			<View style={[{ width: width, height: 160 }]}>
				<SwiperView style={{ height: '100%', flexDirection: 'row' }}>
					<View>
						<Image
							source={{
								uri:
									'http://60.191.15.90:3002/MESHOP01/M00/0A/B8/ywPsn1_bAtOARqAUAACwuamTdaU497.jpg',
							}}
							style={[{ width, height: '100%', backgroundColor: '#FFF' }]}
						/>
					</View>
					<View>
						<Image
							source={{
								uri:
									'http://60.191.15.90:3002/MESHOP01/M00/08/9D/ywPsoF9izQWAIxmYAAKV3ad0SUc498.png',
							}}
							style={[{ width, height: '100%', backgroundColor: 'red' }]}
						/>
					</View>
					<View>
						<Image
							source={{
								uri:
									'http://60.191.15.90:3002/MESHOP01/M00/08/9E/ywPsoV9izReAfLZnAAJZB3CcX_g050.png',
							}}
							style={[{ width, height: '100%', backgroundColor: 'green' }]}
						/>
					</View>
					<View>
						<Image
							source={{
								uri:
									'http://60.191.15.90:3002/MESHOP01/M00/0B/A0/ywPsoV_4KnqAEC9dAAF6UfZexB8743.png',
							}}
							style={[{ width, height: '100%', backgroundColor: '#FFF' }]}
						/>
					</View>
				</SwiperView>
			</View>
		);
	}
}
